package com.app.micaihu.app;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Build;
import android.os.Environment;

import androidx.annotation.NonNull;

import com.alibaba.sdk.android.feedback.impl.FeedbackAPI;
import com.app.micaihu.BuildConfig;
import com.app.micaihu.R;
import com.app.micaihu.ad.toutiao.TTAdManagerHolder;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.StyleConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.IPushManager;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.ForegroundCallbacks;
import com.app.micaihu.view.lunch.LunchActivity;
import com.app.micaihu.view.main.view.ClassFooter;
import com.app.micaihu.view.main.view.ClassHeader;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.CacheType;
import com.app.okhttplib.annotation.Encoding;
import com.app.okhttplib.interceptor.HttpInterceptor;
import com.app.utils.ChannelUtil;
import com.app.utils.NetUtils;
import com.app.utils.util.AppTools;
import com.app.utils.util.AppUtils;
import com.app.utils.util.LauncherUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.file.AppFileUtils;
import com.app.utils.util.image.FrescoHelper;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.CrashUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.Utils;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.InitListener;
import com.getui.gs.ias.core.GsConfig;
import com.getui.gs.sdk.GsManager;
import com.scwang.smart.refresh.layout.SmartRefreshLayout;
import com.scwang.smart.refresh.layout.api.RefreshFooter;
import com.scwang.smart.refresh.layout.api.RefreshHeader;
import com.scwang.smart.refresh.layout.api.RefreshLayout;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshFooterCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshHeaderCreator;
import com.scwang.smart.refresh.layout.listener.DefaultRefreshInitializer;
import com.tencent.smtt.sdk.QbSdk;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;

import java.io.File;
import java.util.List;

/**
 * 程序自定义Applicaiton
 * Created by kai on 2016/6/12.
 */
public class AppApplication extends Application {

    private static AppApplication mAppApplication;//唯一实例
    public static boolean isOpenApp;//是否打开app

    @Override
    public void onCreate() {
        super.onCreate();
        String processName = getProcessName(this);
        if (!"com.app.micaihu".equals(processName)) {
            return;
        }
        mAppApplication = this;
        initUtils();
        //设置程序的异常处理器
        initCatchExcep();
        //初始化工具库
        initAppUitls();
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
            //设置是否改变通知栏的颜色
            AppConfigTools.isSetNotify = true;
        }
        //初始化统计配置
        initTongji();
        //初始化用户配置
        initUserConfig();
        //初始化加载图片工具
        initLoadImgUtils();
        //初始化友盟登陆分享
        initUmeng();
        //初始化OkHTTP
        initOkHttp();
        //本地登录
        UserInforManager.getInstance().getUserInfor();
        initBack();
        initFeedbackAPI();
        initX5();
        initSy();
        TTAdManagerHolder.init();
//        LoadMoreModuleConfig.setDefLoadMoreView(new CustomLoadMoreView());
    }

    private void initUtils() {
        Utils.init(this);
        LogUtils.Config config = com.blankj.utilcode.util.LogUtils.getConfig();
        config.setBorderSwitch(false);
    }

    private void initSy() {
        OneKeyLoginManager.getInstance().init(getApplicationContext(), "Gf8xyZs6", new InitListener() {
            @Override
            public void getInitStatus(int code, String result) {
                com.blankj.utilcode.util.LogUtils.e("VVV", "初始化： code==" + code + "  result==" + result);
            }
        });
    }

    private void initBack() {
        ForegroundCallbacks.init(this);
        ForegroundCallbacks.get().addListener(new ForegroundCallbacks.Listener() {
            @Override
            public void onBecameForeground() {//当前程序切换到前台
                /**  GsonPostRequest
                 * 后台运行操作10分钟之后再次切换到app显示开屏画面，设置开关和每天展示的次数
                 */
                boolean isShowLunch = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isShowLunch, false); //应用切到后台 是否展示 启动页
                if (isShowLunch) {
                    int displayServiceTimes = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.displayServiceTimes, 0); //应用切到后台 服务器返回的每天展示的次数
                    int displayLocalTimes = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.displayLocalTimes, 0); //应用切到后台 本地展示的次数
                    if (LauncherUtils.isShowLauncher && (displayServiceTimes >= displayLocalTimes)) {
                        displayLocalTimes++;
                        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.displayLocalTimes, displayLocalTimes);
                        //app回到前台 --- 打开启动页
                        Intent intent = new Intent(getApplicationContext(), LunchActivity.class);
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        getApplicationContext().startActivity(intent);
                    } else {
                        //app回到前台 --- 时间不到重置变量
                        LauncherUtils.getInstance().resetMessages();
                    }
                }


            }

            @Override
            public void onBecameBackground() {  //当前程序切换到后台  重新计时
                boolean isShowLunch = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isShowLunch, false); //应用切到后台 是否展示 启动页
                if (isShowLunch) {
                    int displayServiceTimes = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.displayServiceTimes, 0); //应用切到后台 服务器返回的每天展示的次数
                    int displayLocalTimes = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.displayLocalTimes, 0); //应用切到后台 本地展示的次数
                    if (displayServiceTimes >= displayLocalTimes) {
                        int backgroundTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.backgroundTime, 0);//应用切到后台 显示启动页的时间
                        LauncherUtils.getInstance().resetMessages();
                        LauncherUtils.getInstance().postDelayed(backgroundTime);
                    }
                }
            }
        });
    }

    private void initX5() {
        QbSdk.PreInitCallback callback = new QbSdk.PreInitCallback() {

            @Override
            public void onCoreInitFinished() {
                com.blankj.utilcode.util.LogUtils.e("x5 onCoreInitFinished()");
            }

            @Override
            public void onViewInitFinished(boolean b) {
                com.blankj.utilcode.util.LogUtils.e("x5->" + b);
            }
        };
        QbSdk.initX5Environment(this, callback);
    }


    /**
     * 初始化 OK工具类
     */
    private void initOkHttp() {
        String cacheDir = Environment.getExternalStorageDirectory().getPath();
        OkHttpUtil.init(this)
                .setConnectTimeout(15)//连接超时时间
                .setWriteTimeout(15)//写超时时间
                .setReadTimeout(15)//读超时时间
                .setMaxCacheSize(10 * 1024 * 1024)//缓存空间大小
                .setCacheType(CacheType.FORCE_NETWORK)//缓存类型
                .setHttpLogTAG("HttpLog")//设置请求日志标识
                .setIsGzip(false)//Gzip压缩，需要服务端支持
                .setShowHttpLog(true)//显示请求日志
                .setShowLifecycleLog(true)//显示Activity销毁日志
                .setRetryOnConnectionFailure(false)//失败后不自动重连
                .setCachedDir(new File(cacheDir, "okHttp_cache"))//缓存目录
                .setDownloadFileDir(DownloadUtils.DOWNLOAD_FILEDIR)//文件下载保存目录
                .setResponseEncoding(Encoding.UTF_8)//设置全局的服务器响应编码
                .addResultInterceptor(HttpInterceptor.ResultInterceptor)//请求结果拦截器
                .addExceptionInterceptor(HttpInterceptor.ExceptionInterceptor)//请求链路异常拦截器
//                .setCookieJar(new PersistentCookieJar(new SetCookieCache(), new SharedPrefsCookiePersistor(this)))//持久化cookie
                .build();
    }

    /**
     * 获取当前进程的name
     *
     * @param context
     * @return
     */
    private String getProcessName(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningApps = am.getRunningAppProcesses();
        if (runningApps == null) {
            return null;
        }
        for (ActivityManager.RunningAppProcessInfo proInfo : runningApps) {
            if (proInfo.pid == android.os.Process.myPid()) {
                if (proInfo.processName != null) {
                    return proInfo.processName;
                }
            }
        }
        return null;
    }

    /**
     * 配置统计
     */
    private void initTongji() {
        String channel = ChannelUtil.getChannel(this, "no_channel");//获取渠道,默认为test

        StatService.setAppChannel(this, channel, true);// 初始化百度统计渠道
        //自动埋点
        StatService.autoTrace(this, true, false);
        StatService.setDebugOn(BuildConfig.DEBUG);
        //友盟推送渠道
        IPushManager.getInstance().setPushChannel(channel);

        // 个推 统计
        GsConfig.setInstallChannel(channel);
        GsConfig.setDebugEnable(BuildConfig.DEBUG);
        GsManager.getInstance().init(this);
    }


    private void initFeedbackAPI() {
        FeedbackAPI.init(this, "23548167", "bc9576a6f26e1cb7c0b6121a6e6613ab");
        FeedbackAPI.addErrorCallback((context, errorMessage, code) -> com.blankj.utilcode.util.LogUtils.e("errorMessage->" + errorMessage + " code->" + code));
        FeedbackAPI.addLeaveCallback(() -> {
            com.blankj.utilcode.util.LogUtils.e("FeedbackAPI custom leave callback");
            return null;
        });
    }

    /**
     * 初始化工具类
     */
    private void initAppUitls() {
        AppUtils.getInstance().setContext(mAppApplication);
        AppUtils.getInstance().setmDebug(BuildConfig.DEBUG);
        //添加表情
        AppUtils.getInstance().addExpresstion(StyleConstant.piclist1_res());
        AppUtils.getInstance().addExpresstion(StyleConstant.piclist2_res());

    }

    /**
     * 初始化用户配置
     */
    private void initUserConfig() {
        // 初始化用户配置
        SharedPreferences sp = AppConfigManager.getInstance().getConfigSP();
        UserConfigTools.textSize = sp.getInt(ConfigKeyConstant.option_textSize, 1);
        UserConfigTools.isUseWifi = sp.getBoolean(ConfigKeyConstant.option_isWifi, false);
        UserConfigTools.isAutoPaly = sp.getBoolean(ConfigKeyConstant.autoPaly, true);
//        UserConfigTools.screen_brightnes = sp.getInt(ConfigKeyConstant.option_Screen_brightnes, -2);
//        UserConfigTools.isSummary = sp.getBoolean(ConfigKeyConstant.option_isSummary, false);

        if (sp.getBoolean(ConfigKeyConstant.isFristOpenApp, true)) {
            //如果是第一次打开app 则清理缓存
            new Thread() {
                public void run() {
                    AppFileUtils.clearCache(new File(AppConfigTools.SDCARDPATH1));// 清除所有缓存图片
                    AppFileUtils.clearCache(new File(AppConfigTools.SDCARDPATH));// 清除所有缓存图片
                }

            }.start();
            sp.edit().putBoolean(ConfigKeyConstant.isFristOpenApp, false).apply();
        }

        if (sp.getBoolean(ConfigKeyConstant.option_isPull, true)) {
//            //注册小米推送
//            IPushManager.getInstance().initMiPush();
//            //友盟推送的自定义消息处理
//            IPushManager.getInstance().initUmengPush();
            IPushManager.getInstance().initDoublePushByBuildMode();
        }

        setLoadImg();//设置当前网络是否允许加载图片

    }

    /**
     * 设置当前网络是否加载
     */
    private void setLoadImg() {
        int netType = NetUtils.getNetworkType();//获取当前网络类型
        if (netType == NetUtils.NETTYPE_CM && UserConfigTools.isUseWifi) {
            //当前网络为移动网络并且开启了仅wifi加载图片  不允许加载图片
            LoadImageUtils.getInstance().setIsLoadImg(false);
            AppConfigTools.isLoadImage = false;

        } else {
            LoadImageUtils.getInstance().setIsLoadImg(true);
            AppConfigTools.isLoadImage = true;
        }
    }

    /**
     * 初始化友盟登陆分享
     * 的分享和第三方登录
     */
    private void initUmeng() {
        String umengKey = "57753cb067e58e8ec3005876";
        UMConfigure.preInit(this, umengKey, ChannelUtil.getChannel());
        UMConfigure.init(this, umengKey, ChannelUtil.getChannel(), UMConfigure.DEVICE_TYPE_PHONE, "");
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        UMConfigure.setLogEnabled(BuildConfig.DEBUG);
        // 支持在子进程中统计自定义事件
        UMConfigure.setProcessEvent(true);
        //微信 appid appsecret
        PlatformConfig.setWeixin(AppConfigTools.WECHAT_ID, AppConfigTools.WECHAT_SECRET);
        PlatformConfig.setQQZone(AppConfigTools.QQ_APPID, AppConfigTools.QQ_APPKEY);
        PlatformConfig.setSinaWeibo(AppConfigTools.SINA_APPID, AppConfigTools.SINA_APPKEY, "http://sns.whalecloud.com");
        UMConfigure.getOaid(this, s -> {
            LogUtils.e("getOaid->" + s);
            if (com.blankj.utilcode.util.StringUtils.isEmpty(s)) {
                String oaIdKey = SPUtils.getInstance().getString(AppTools.oaIdKey);
                LogUtils.e("OnIdsAvalidKey->" + oaIdKey);
                if (StringUtils.isEmpty(oaIdKey)) {
                    SPUtils.getInstance().put(AppTools.oaIdKey, AppTools.getDeviceId());
                }
            } else {
                SPUtils.getInstance().put(AppTools.oaIdKey, s);
            }
        });
    }

    /**
     * 初始化加载图片工具
     */
    private void initLoadImgUtils() {
        //初始化fresco配置
        LoadImageUtils.getInstance().setImgCachePath(AppConfigTools.ALLIMGPATHFloder);
        LoadImageUtils.getInstance().setImgCacheName(AppConfigTools.IMGCACHE);
        LoadImageUtils.getInstance().setImgCachePackage(AppConfigTools.RESOUCENAME);
        LoadImageUtils.getInstance().setHeaderParam(URIContant.REALMNAME);
        LoadImageUtils.getInstance().initFresco();
    }


    /**
     * 注册全局异常
     */
    private void initCatchExcep() {
        if (BuildConfig.DEBUG) {
            return;
        }
        CrashUtils.init(new CrashUtils.OnCrashListener() {
            @Override
            public void onCrash(CrashUtils.CrashInfo crashInfo) {
                com.blankj.utilcode.util.LogUtils.e("onCrash", crashInfo);
                MobclickAgent.onKillProcess(getApplicationContext());
            }
        });
    }

    /***************公共方法 start *********************/

    /**
     * 获取唯一实例
     *
     * @return
     */
    public static AppApplication getInstance() {
        return mAppApplication;
    }


    /***************
     * 公共方法 end
     *********************/


    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);

        //支持5.0以下分包
//        MultiDex.install(this);
    }


    /**
     * 低内存时候 清除缓存
     */
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        FrescoHelper.clearAllMemory();

    }

    /**
     * 低内存时候 清除缓存
     */
    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        FrescoHelper.TrimMemory(level);
    }

    //static 代码段可以防止内存泄露
    static {
        SmartRefreshLayout.setDefaultRefreshInitializer(new DefaultRefreshInitializer() {
            @Override
            public void initialize(@NonNull Context context, @NonNull RefreshLayout layout) {
                //全局设置（优先级最低）
                layout.setEnableScrollContentWhenRefreshed(true);
                layout.setEnableScrollContentWhenLoaded(true);
                layout.setEnableFooterFollowWhenNoMoreData(true);
//                layout.setEnableLoadMoreWhenContentNotFull(false);
                layout.setEnableLoadMore(false);
                layout.setEnableAutoLoadMore(false);
                layout.setDisableContentWhenRefresh(true);
                layout.setPrimaryColorsId(R.color.common_bg_color_5);//全局设置主题颜色
            }
        });
        //设置全局的Header构建器
        SmartRefreshLayout.setDefaultRefreshHeaderCreator(new DefaultRefreshHeaderCreator() {
            @NonNull
            @Override
            public RefreshHeader createRefreshHeader(@NonNull Context context, @NonNull RefreshLayout layout) {

//                classicsHeader.setArrowResource(R.drawable.infor_loading);
//                classicsHeader.setDrawableProgressSize(30);
//                classicsHeader.setDrawableArrowSize(30);
//                classicsHeader.setEnableLastTime(false);
//                classicsHeader.setTextSizeTitle(TypedValue.COMPLEX_UNIT_DIP, 13);//设置标题文字大小
//                classicsHeader.setAccentColor(ColorUtils.getColor(R.color.color888));
//                classicsHeader.setDrawableMarginRight(8);
                return new ClassHeader(context);//.setTimeFormat(new DynamicTimeFormat("更新于 %s"));//指定为经典Header，默认是 贝塞尔雷达Header
            }
        });
        //设置全局的Footer构建器
        SmartRefreshLayout.setDefaultRefreshFooterCreator(new DefaultRefreshFooterCreator() {
            @NonNull
            @Override
            public RefreshFooter createRefreshFooter(@NonNull Context context, @NonNull RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassFooter(context);
            }
        });
    }
}
